package com.bmp.dao.impl;

import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Component;

import com.bmp.dao.ProjectDao;
import com.bmp.model.Project;
import com.bmp.model.vo.ProjectVoProStatus;
import com.bmp.util.HibernateUtil;

@Component("projectDao")
public class ProjectDaoImpl implements ProjectDao {
	private HibernateTemplate hibernateTemplate;

	public HibernateTemplate getHibernateTemplate() {
		return hibernateTemplate;
	}

	@Resource
	public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
		this.hibernateTemplate = hibernateTemplate;
	}

	public void deleteProjectById(int id) {
		Project p = this.getProjectById(id);
		this.hibernateTemplate.delete(p);
	}

	public Project getProjectById(int id) {
		return (Project)this.hibernateTemplate.get(Project.class, id);
	}

	public void insertProject(Project p) {
		this.hibernateTemplate.save(p);
	}

	public void updateProject(Project p) {
		this.hibernateTemplate.update(p);
	}
	
	//根据page和rows获取工程信息
	@SuppressWarnings("unchecked")
	public List<ProjectVoProStatus> getProject(int page, int rows) {
		List<ProjectVoProStatus> list = null;
		SessionFactory sf = HibernateUtil.getSessionFactory();
		Session session = sf.getCurrentSession();
		session.beginTransaction();
		String sql = "select new com.bmp.model.vo.ProjectVoProStatus(p.id,p.p_name,p.p_des,p.start_time,ps.status) from Project p,ProStatus ps where p.status_id = ps.id";
		list = session.createQuery(sql).setFirstResult((page-1)*rows).setMaxResults(rows).list();
		session.getTransaction().commit();
		System.out.println("getProject");
		return list;
	}

	//获取总记录数
	public int getTotalPages() {
		SessionFactory sf = HibernateUtil.getSessionFactory();
		Session session = sf.getCurrentSession();
		session.beginTransaction();
		String sql = "select count(*) from Project p";
		long count = (Long)session.createQuery(sql).uniqueResult();
		session.getTransaction().commit();
		System.out.println(count);
		return (int)count;
	}

	public List<Project> getAllProjects() {
		SessionFactory sf = HibernateUtil.getSessionFactory();
		Session session = sf.getCurrentSession();
		session.beginTransaction();
		String sql = "from Project p";
		List<Project> projects = session.createQuery(sql).list();
		return projects;
	}

}
